<?php

namespace App\Ant;

use App\Models\Media;
use Carbon\Carbon;
use Dingo\Api\Http\FormRequest;
use Illuminate\Http\UploadedFile;

trait WithUpload
{

    public function addUpload(FormRequest $request)
    {
        $files = array_keys($request->validated());
        foreach ($files as $key => $file) {
            if (!$this->isFile($file)) {
                unset($files[$key]);
            }
        }
        return $this->uploadFiles($request, $files);
    }

    protected function uploadFiles(FormRequest $request, array $files = [])
    {
        if (count($files) == 0) {
            return true;
        }
        $fileDir = Carbon::now()->format('Ymd');
        foreach ($files as $file) {
            $getFile = $request->file($file);
            $media = new Media([
                'name' => $getFile->getClientOriginalName(),
                'mime' => $getFile->getMimeType(),
                'size' => $getFile->getSize(),
            ]);
            $path = $getFile->storeAs($file . '/' . $fileDir, $this->setFileName($getFile),'public');
            $media->path = $path;
            $media->save();
        }
        return $media;
    }

    protected function setFileName(UploadedFile $file)
    {
        return str_random(16) . '.' . $file->clientExtension();
    }

    private function isFile($file_name)
    {
        return request()->hasFile($file_name);
    }
}